//
//  tableviewController.swift
//  ShopIOS
//
//  Created by Apple on 2019/8/2.
//  Copyright © 2019 Apple. All rights reserved.
//

import UIKit

class CollectionViewController: UIViewController {
    @IBOutlet weak var tableview: UITableView!
    @IBOutlet weak var uv_back: UIView!
    var pageNo=1
    var productList=[CollectionData]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        uv_back.addOnClickListener(target: self, action: #selector(back))
        tableview.register(UINib(nibName: "CollectionTableViewCell", bundle: nil), forCellReuseIdentifier: "re")
        tableview.separatorStyle = .none
        
        //refresh
        let header = TTRefreshHeader.init(refreshingBlock: {[weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = 1
            strongSelf.tableview.mj_footer.state = .idle
            strongSelf.tableview.mj_header.endRefreshing()
            strongSelf.loaddata()
        })
        
        tableview.mj_header = header;
        
        let footer = TTRefreshFooter  {  [weak self] in
            guard let strongSelf = self else{return}
            strongSelf.pageNo = strongSelf.pageNo + 1
            strongSelf.loaddata();
        }
        
        tableview.mj_footer = footer
        tableview.mj_footer.isHidden = true
        
        loaddata()
        // Do any additional setup after loading the view.
    }
    @objc func back(){
        self.navigationController?.popViewController(animated: true)
    }
    func loaddata(){
        var d = ["app_key":app_key,
                 "pageSize":"20",
                 "pageNo":"\(pageNo)",
            "userkey":userkey!,
            "timestamp":getTimestamp()
            ] as [String : String]
        let sign=SignTopRequest(params: d)
        d["sign"]=sign
        AlamofireHelper.get(url: GetUserCollectionProduct, parameters: d, successHandler: {[weak self](res)in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.pageNo == 1{ ss.productList.removeAll()}
            
            if ss.tableview.mj_header.isRefreshing(){
                ss.tableview.mj_header.endRefreshing()
            }else if ss.tableview.mj_footer.isRefreshing() {
                ss.tableview.mj_footer.endRefreshing()
                
            }
            let collectionResult=CollectionResult.init(json: res)
            
            
            if collectionResult.Data.count>0 {
                if ss.tableview.mj_footer.isHidden && collectionResult.Data.count > 0 {
                    ss.tableview.mj_footer.isHidden = false
                }
                ss.productList.insert(contentsOf: collectionResult.Data, at: ss.productList.count)
                if ss.productList.count < 20 {
                    ss.tableview.mj_footer.state = .noMoreData
                }
            }else {
                ss.tableview.mj_footer.state = .noMoreData
            }
            ss.tableview.reloadData()
        }){[weak self] (error) in
            HUD.dismiss()
            guard let ss = self else {return}
            if ss.tableview.mj_header.isRefreshing(){ss.tableview.mj_header.endRefreshing()}
            else if ss.tableview.mj_footer.isRefreshing() {ss.tableview.mj_footer.endRefreshing()}
        }
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
extension CollectionViewController:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return productList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell=tableView.dequeueReusableCell(withIdentifier: "re") as! CollectionTableViewCell
        let item=productList[indexPath.row]
        if item.Image != nil{
            cell.iv_img.setImage(path: URL.init(string: item.Image!)!)
        }
        cell.lb_name.text=item.ProductName
        cell.lb_price.text="￥\(item.SalePrice ?? "")"
        cell.btn_similar.layer.cornerRadius=5
        cell.btn_similar.border(color: .lightGray, width: 1, type: UIBorderSideType.UIBorderSideTypeAll, cornerRadius: 13)
        cell.btn_similar.contentEdgeInsets=UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
        
        cell.btn_similar.addTarget(self, action: #selector(similar(sender:)), for: UIControl.Event.touchUpInside)
        cell.btn_similar.tag = indexPath.row
        
        cell.selectionStyle = .none
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.navigationController?.pushViewController(ProductDetailViewController(pid: "\(productList[indexPath.row].Id)"), animated: true)
    }
    @objc func similar(sender:UIButton){
        let item=productList[sender.tag]
        self.navigationController?.pushViewController(SimilarViewController(productId: "\(item.Id)", categoryId: "\(item.categoryId)"), animated: true)
    }
}
